import React, { useState } from 'react';
import {Button, Table, Modal, Form, Input, Select, DatePicker, Divider, Tag, Card, Empty} from 'antd';
import { PlusOutlined } from '@ant-design/icons';

const { Option } = Select;

// 通用模板字段
const COMMON_FIELDS = [
    { id: 'code', name: '编号', type: 'text' },
    { id: 'amount', name: '金额', type: 'number' },
    { id: 'tax', name: '税费', type: 'number' },
    { id: 'expressFee', name: '快递费', type: 'number' },
    { id: 'total', name: '总价', type: 'number' },
    { id: 'supplier', name: '供应商', type: 'text' },
    { id: 'purchaseTime', name: '购买时间', type: 'date' },
    { id: 'paymentTime', name: '付款时间', type: 'date' },
    { id: 'updateTime', name: '更新时间', type: 'date' },
    { id: 'otherFee', name: '其他费用', type: 'number' },
    { id: 'status', name: '状态', type: 'select' },
    { id: 'purchaser', name: '采购人员', type: 'text' },
    { id: 'remark', name: '备注说明', type: 'textarea' }
];

const TemplateManagement = () => {
    const [templates, setTemplates] = useState([]);
    const [modalVisible, setModalVisible] = useState(false);
    const [templateForm] = Form.useForm();
    const [currentTemplate, setCurrentTemplate] = useState(null);
    const [customFields, setCustomFields] = useState([]);
    const [fieldModalVisible, setFieldModalVisible] = useState(false);
    const [fieldForm] = Form.useForm();

    // 列配置
    const columns = [
        {
            title: '模板名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
            render: (type) => (
                <Tag color={type === '通用' ? 'blue' : 'green'}>{type}</Tag>
            )
        },
        {
            title: '包含字段',
            dataIndex: 'fields',
            key: 'fields',
            render: (fields) => `${fields.length}个字段`,
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Button type="link" onClick={() => editTemplate(record)}>
                    编辑
                </Button>
            ),
        },
    ];

    // 打开创建模板弹窗
    const showModal = () => {
        setCurrentTemplate(null);
        setCustomFields([]);
        templateForm.resetFields();
        setModalVisible(true);
    };

    // 编辑模板
    const editTemplate = (template) => {
        setCurrentTemplate(template);
        setCustomFields(template.customFields || []);
        templateForm.setFieldsValue({
            name: template.name,
            type: template.type
        });
        setModalVisible(true);
    };

    // 保存模板
    const handleSaveTemplate = () => {
        templateForm.validateFields().then(values => {
            const newTemplate = {
                id: currentTemplate ? currentTemplate.id : Date.now(),
                name: values.name,
                type: values.type,
                fields: [...COMMON_FIELDS, ...customFields],
                customFields
            };

            if (currentTemplate) {
                setTemplates(templates.map(t => t.id === currentTemplate.id ? newTemplate : t));
            } else {
                setTemplates([...templates, newTemplate]);
            }

            setModalVisible(false);
        });
    };

    // 添加自定义字段
    const handleAddField = () => {
        fieldForm.validateFields().then(values => {
            const newField = {
                id: `custom_${Date.now()}`,
                name: values.fieldName,
                type: values.fieldType
            };
            setCustomFields([...customFields, newField]);
            fieldForm.resetFields();
            setFieldModalVisible(false);
        });
    };

    // 删除自定义字段
    const handleRemoveField = (id) => {
        setCustomFields(customFields.filter(field => field.id !== id));
    };

    // 渲染字段类型输入组件
    const renderFieldInput = (field) => {
        const type = field.type;
        const commonProps = {
            placeholder: `请输入${field.name}`,
            style: { width: '100%' }
        };

        switch (type) {
            case 'text':
                return <Input {...commonProps} />;
            case 'number':
                return <Input type="number" {...commonProps} />;
            case 'date':
                return <DatePicker {...commonProps} />;
            case 'select':
                return (
                    <Select {...commonProps}>
                        <Option value="pending">待支付</Option>
                        <Option value="paid">已支付</Option>
                        <Option value="canceled">已取消</Option>
                    </Select>
                );
            case 'textarea':
                return <Input.TextArea rows={3} {...commonProps} />;
            default:
                return <Input {...commonProps} />;
        }
    };

    return (
        <div style={{ padding: '20px' }}>
            <Card
                title="费用模板管理"
                extra={
                    <Button
                        type="primary"
                        icon={<PlusOutlined />}
                        onClick={showModal}
                    >
                        创建新模板
                    </Button>
                }
            >
                <Table
                    style={{height: '450px'}}
                    columns={columns}
                    dataSource={templates}
                    rowKey="id"
                    pagination={{
                        showTotal: (total) =>  <Tag color="blue">总数：{total}</Tag>, // 显示总数
                        pageSize: 5,  // 每页显示5条数据
                        showSizeChanger: false, // 可选：隐藏每页显示条数选择器
                        total: templates.length, // 总数据量
                    }}
                    locale={{
                        emptyText: (
                            <div style={{ height: '387px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                <Empty /> {/* Ant Design 的 Empty 组件 */}
                            </div>
                        ),
                    }}
                />
            </Card>

            {/* 创建/编辑模板弹窗 */}
            <Modal
                open={modalVisible}
                title={currentTemplate ? "编辑费用模板" : "创建费用模板"}
                onOk={handleSaveTemplate}
                onCancel={() => setModalVisible(false)}
                width={800}
            >
                <Form form={templateForm} layout="vertical">
                    <Form.Item
                        label="模板名称"
                        name="name"
                        rules={[{ required: true, message: '请输入模板名称' }]}
                    >
                        <Input placeholder="例如：打印费模板" />
                    </Form.Item>

                    <Form.Item
                        label="模板类型"
                        name="type"
                        initialValue="自定义"
                    >
                        <Select disabled>
                            <Option value="通用">通用模板</Option>
                            <Option value="自定义">自定义模板</Option>
                        </Select>
                    </Form.Item>

                    <Divider orientation="left">通用字段</Divider>
                    <div style={{ marginBottom: 24 }}>
                        {COMMON_FIELDS.map(field => (
                            <Tag key={field.id} color="blue">{field.name}</Tag>
                        ))}
                    </div>

                    <Divider orientation="left">
                        自定义字段
                        <Button
                            type="dashed"
                            size="small"
                            style={{ marginLeft: 10 }}
                            onClick={() => setFieldModalVisible(true)}
                        >
                            添加字段
                        </Button>
                    </Divider>

                    {customFields.length > 0 ? (
                        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
                            {customFields.map(field => (
                                <Card
                                    key={field.id}
                                    size="small"
                                    title={field.name}
                                    extra={
                                        <Button
                                            type="link"
                                            danger
                                            size="small"
                                            onClick={() => handleRemoveField(field.id)}
                                        >
                                            删除
                                        </Button>
                                    }
                                >
                                    {renderFieldInput(field)}
                                </Card>
                            ))}
                        </div>
                    ) : (
                        <p style={{ color: '#999', textAlign: 'center' }}>暂无自定义字段</p>
                    )}
                </Form>
            </Modal>

            {/* 添加字段弹窗 */}
            <Modal
                title="添加自定义字段"
                open={fieldModalVisible}
                onOk={handleAddField}
                onCancel={() => setFieldModalVisible(false)}
            >
                <Form form={fieldForm} layout="vertical">
                    <Form.Item
                        label="字段名称"
                        name="fieldName"
                        rules={[{ required: true, message: '请输入字段名称' }]}
                    >
                        <Input placeholder="例如：打印内容" />
                    </Form.Item>
                    <Form.Item
                        label="字段类型"
                        name="fieldType"
                        rules={[{ required: true, message: '请选择字段类型' }]}
                        initialValue="text"
                    >
                        <Select>
                            <Option value="text">文本</Option>
                            <Option value="number">数字</Option>
                            <Option value="date">日期</Option>
                            <Option value="select">下拉选择</Option>
                            <Option value="textarea">多行文本</Option>
                        </Select>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default TemplateManagement;